package com.ygqh.baby.service.impl;

import com.alibaba.fastjson.JSON;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.handler.DefaultPromotionTagHandler;
import com.ygqh.baby.mapper.YgProductPackMapper;
import com.ygqh.baby.mapper.YgProductPackV2Mapper;
import com.ygqh.baby.model.EditProductPackRequest;
import com.ygqh.baby.model.ProductPackQueryRequest;
import com.ygqh.baby.model.YgProductPackExt;
import com.ygqh.baby.model.YgProductPackModel;
import com.ygqh.baby.po.YgProduct;
import com.ygqh.baby.po.YgProductPack;
import com.ygqh.baby.service.YgProductPackDetailService;
import com.ygqh.baby.service.YgProductPackV2Service;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.ExceptionUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @author admin
 */
@Service
public class YgProductPackV2ServiceImpl implements YgProductPackV2Service {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private YgProductPackMapper ygProductPackMapper;
    @Autowired
    private YgProductPackV2Mapper ygProductPackV2Mapper;

    @Autowired
    private YgProductPackDetailService ygProductPackDetailService;

    @Autowired
    private DefaultPromotionTagHandler defaultPromotionTagHandler;


    @Override
    public YgProductPack findById(Long id) {
        return ygProductPackMapper.selectByPrimaryKey(id);
    }

    @Override
    public int save(YgProductPack ygProductPack) {
        return ygProductPackMapper.insertSelective(ygProductPack);
    }

    @Override
    public int update(YgProductPack ygProductPack) {
        return ygProductPackMapper.updateByPrimaryKeySelective(ygProductPack);
    }

    @Override
    public ResultSet<YgProductPackExt> search(ProductPackQueryRequest queryRequest) {

        int count = ygProductPackV2Mapper.countSuperV2(queryRequest);
        List<YgProductPackExt> list;
        if (count > 0) {
            list = ygProductPackV2Mapper.selectSuperV2(queryRequest);
        } else {
            list = Collections.emptyList();
        }
        return new ResultSet<>(count, list);
    }

    @Override
    public int saveOrUpdate(YgProductPack ygProductPack) {
        int r = 0;
        if (ygProductPack.getId() != null) {
            r = this.update(ygProductPack);
        } else {
            r = this.save(ygProductPack);
        }
        return r;
    }

    @Override
    public ResponseEntity editProductPack(EditProductPackRequest packRequest) {
        logger.info("editProductPack param > {}", packRequest);
        ResponseEntity responseEntity = null;
        try {
            responseEntity = checkPack(packRequest);
            if (!responseEntity.isSuccess()) {
                return responseEntity;
            }
            YgProductPack productPack = new YgProductPack();
            BeanUtils.copyProperties(packRequest, productPack);
            productPack.setProductIds(StringUtil.join(packRequest.getProductIds(), ",".charAt(0)));
            productPack.setUpdateBy(packRequest.getHandler());
            productPack.setUpdateTime(new Date());
            if (packRequest.getPackId() != null) {
                productPack.setId(packRequest.getPackId());
                updateProductPack(productPack, packRequest.getProductIds());
            } else {
                productPack.setCreateBy(packRequest.getHandler());
                productPack.setCreateTime(new Date());
                addProductPack(productPack, packRequest.getProductIds());
            }
        } catch (Exception e) {
            responseEntity = ResponseEntity.error("editProductPack fail");
            logger.error("editProductPack fail。> {}", ExceptionUtil.getExceptionMsg(e));
            e.printStackTrace();
        } finally {
            logger.info("editProductPack response > {}", JSON.toJSONString(responseEntity));
        }
        return responseEntity;
    }

    @Override
    public List<YgProduct> findProductByBack(Long packId) {
        return ygProductPackDetailService.findProductByBack(packId);
    }

    @Override
    public List<YgProduct> findProductListWithPackSign(QueryInfo queryInfo, String productName, Long groupId, ProductStatus productStatus,
                                                       Long supplierId, Long packId) {

        return ygProductPackV2Mapper.selectProductListWithPackSign(queryInfo, productName, groupId, productStatus, supplierId, packId);
    }

    @Override
    public YgProductPackExt getProductPackInfo(Long packId) {
        return ygProductPackV2Mapper.getProductPackInfo(packId);
    }

    @Override
    public List<YgProductPackModel> findPackList(Long productId, Date currentDate) {
        return ygProductPackV2Mapper.selectPackList(productId, currentDate);
    }

    @Override
    public List<Long> findProductIdsByPackId(Long packId) {
        return ygProductPackV2Mapper.findProductIdsByPackId(packId);
    }

    @Override
    public List<YgProductPack> findByUpdateTime(Date startTime, Date endTime) {
        return ygProductPackV2Mapper.selectByUpdateTime(startTime, endTime);
    }

    @Override
    public List<YgProductPack> findPackListByProductId(PromotionStatus promotionStatus, Long... productIds) {
        return ygProductPackV2Mapper.selectPackListByProductIds(promotionStatus.name(), DateConvertUtils.getDateStart(new Date()), productIds);
    }

    private void updateProductPack(YgProductPack productPack, Long[] productIds) {
        this.update(productPack);
        ygProductPackDetailService.updateProductPackDetail(productPack.getId(), productIds, productPack.getUpdateBy());

    }

    private void addProductPack(YgProductPack productPack, Long[] productIds) {
        this.save(productPack);
        ygProductPackDetailService.addProductPackDetail(productPack.getId(), productIds, productPack.getCreateBy());
    }

    private ResponseEntity checkPack(EditProductPackRequest packRequest) {
        if (packRequest.getPackPrice() == null) {
            return ResponseEntity.error("请设置自选包价格", null);
        }
        if (packRequest.getProductAmount() == null) {
            return ResponseEntity.error("请设置自选包数量", null);
        }
        if (packRequest.getStartDate() == null || packRequest.getEndDate() == null) {
            return ResponseEntity.error("请设置活动时间", null);
        }
        if (packRequest.getSupplierId() == null) {
            return ResponseEntity.error("商家id不能为空", null);
        }
        if (packRequest.getProductIds() == null || packRequest.getProductIds().length == 0) {
            return ResponseEntity.error("请设置自选包商品", null);
        }
        List<Long> inOtherPack = ygProductPackDetailService.getProductIdsInOtherPack(packRequest.getPackId(), packRequest.getProductIds(),
                packRequest.getStartDate(), packRequest.getEndDate());
        if (CollectionUtils.isNotEmpty(inOtherPack)) {
            return ResponseEntity.error("商品与其他自选包冲突。" + inOtherPack, null);
        }
        return ResponseEntity.success();
    }

}
